package dm.model;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.IdUtil;
import dm.cont.MyConfig;
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.CSVLoader;

public class FileUtiles {
	@Autowired
	private JdbcTemplate jdbcTemp;
 

	/****
	 * 把文件转成arff并入库
	 * 
	 * @param file
	 */
	public static boolean csv2Arff(MultipartFile mutfile, String filepath3, String filename) {

		try {
			// 把文件存到本地
			File file = new File(filename);
			mutfile.transferTo(file);
			return csv2Arff(filename, filepath3);
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}

	public static boolean csv2Arff(String filename, String arfffile) {
		try {
			CSVLoader loader = new CSVLoader();
			loader.setSource(new File(filename));
			Instances data = loader.getDataSet();

			ArffSaver saver = new ArffSaver();
			saver.setInstances(data);
			saver.setFile(new File(arfffile));
			saver.writeBatch();
			// 成功
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			// 失败
			return false;
		}

	}

	/***
	 * 读取csv文件
	 * 
	 * @param filename
	 */
	public static void readcsv(String filename) {
		CsvReader read = CsvUtil.getReader();
		File csvfile = new File(filename);
		CsvData csvdata = read.read(csvfile);
		Iterator<CsvRow> csvrow = csvdata.iterator();
		while (csvrow.hasNext()) {
			CsvRow row = csvrow.next();
			for (String s : row.getRawList()) {
				System.out.println(s);
			}

		}
	}

	public static void main(String[] args) throws IOException {
		String filename = "F:\\123.csv";
		String filename2 = "F:\\123_1.arff";
		// readcsv(filename);

	}
}
